<?php
class OrderAction extends Action{
	//显示订单模板
	public function index(){
		$data=array();
		$db=M('goods');
		foreach($_SESSION['car'] as $k=>$v){
			$name=$db->where(array('id'=>$v['gid']))->getField('name');
			$data[$k]['name']=$name."(".$v['guige'].")";
			$data[$k]['price']=$v['price'];
			$data[$k]['num']=$v['num'];
		}
		$this->data=$data;
		$this->display();
	}
	/**
	 * 生成订单
	 */
	public function createOrder(){
		if(!$this->isPost()){
			halt('页面不存在');
		}
		$orderList=array();
		foreach($_SESSION['car'] as $v){
			$orderList[]=array(
				'quantity'=>$v['num'],
				'subtotal'=>$v['num']*$v['price'],
				'gid'=>$v['gid'],
				'mark'=>$v['guige']
				);
		}
		$total=$_SESSION['allprice'];
		$address=htmlspecialchars($_POST['province']).htmlspecialchars($_POST['city']).htmlspecialchars($_POST['hometown']).htmlspecialchars($_POST['address']);
		$data=array(
			'number'=>'suning'.time().mt_rand(0,999),
			'consignee'=>htmlspecialchars($_POST['consignee']),
			'address'=>$address,
			'total'=>$total,
			'time'=>time(),
			'uid'=>$_SESSION['uid'],
			'order_list'=>$orderList
			);
		/*p($_SESSION);
		die;*/
		$db=D('OrderRelation');
		$id=$db->relation(true)->add($data);
		if($id){
			unset($_SESSION['car']);
			unset($_SESSION['allprice']);
			unset($_SESSION['car_count']);
			redirect(U('ordered',array('id'=>$id)));
		}else{
			$this->error('生成订单失败，请重试');
		}
		
	}
	//支付成功后改变订单状态
	public function status(){
		if(!$this->isAjax()){
			halt('页面不存在');
		}
		$id=intval($_POST['oid']);
		$uid=intval($_SESSION['uid']);
		$db=M('order');
		$where=array('id'=>$id,'uid'=>$uid);
		$rows=$db->where($where)->data(array('status'=>2))->save();
		if($rows){
			echo 1;
		}else{
			echo 0;
		}
	}
	public function ordered(){
		if(!$this->isGet()){
			halt('页面不存在');
		}
		$oid=intval($_GET['id']);
		$db=M('order');
		$status=$db->where(array('id'=>$oid))->getField('status');
		/*echo $status;die;*/
		$this->status=$status;
		$this->display();
	}
}
?>